<template>
  <MenuPage>
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="addOrUpdateTemplate()">新建{{pageTitle}}</Button>
      <Select filterable
        v-model="query.rangeId"
        style="margin-left:15px;width:150px"
        placeholder="所属靶场"
        clearable
        v-if="distributedRange && $store.state.common.showDistributed"
        @on-change="temOnChange(1)"
      >
        <Option
          v-for="(items, index) in rangeAllList"
          :value="items.id"
          :key="index + 'range'"
          >{{ items.name }}</Option
        >
      </Select>
      <Select filterable
        clearable
        placeholder="可见范围"
        v-model="query.visibility"
        style="width: 150px;margin-left:15px;"
        @on-change="temOnChange(1)"
      >
        <Option value="public">系统</Option>
        <Option value="share">单位</Option>
        <Option value="private">个人</Option>
      </Select>
      <Input
        v-model.trim="query.name"
        placeholder="模板名称"
        clearable
        @on-change="debounceSearch"
        style="width: 200px;margin: 0 15px;"
      />
      <Button @click="refreshTem"><i class="el-icon-refresh-right"/></Button>
    </template>
    <template slot="content">
      <div class="table-wrap">
        <template v-if="templateList.length > 0">
        <Row :gutter="24" style="padding-top: 10px">
          <Col :span="spanNum" class="exper-wrap" v-for="(item, key) in templateList" :key="key">
            <div @mouseenter="enter(key)" @mouseleave="leave(key)">
              <img class="exper-img" :src="setFiles(item.picUrl)" @click="showBigImg(item.picUrl)" :onerror="defaultTemplateImg"/>
              <div class="exper-bottom">
                <div class="exper-name" :title="item.name">{{ item.name }}</div>
                <div style="display: flex;justify-content: space-between;margin-bottom: 5px">
                  <div style="font-size: 12px;">
                    <img src="../../assets/exper/avtar.png" alt="头像" class="exper-avtar" />
                    {{ item.creatorName }}
                  </div>
                  <div style="font-size: 12px;">
                    <img src="../../assets/exper/see.png" alt="share" class="ses-icon" />
                    {{ filterVisible(item.visibility) }}
                  </div>
                </div>
                <div style="font-size: 12px;">
                  <img src="../../assets/exper/time-icon.png" alt="time" class="time-icon" />{{
                    item.created
                  }}
                </div>
                <div class="oper-btn" v-show="item.showFlag">
                  <Button
                    type="primary"
                    ghost
                    style="margin-right: 10px;"
                    size="small"
                    @click="creatProByTemp(item)"
                    >创建工程</Button
                  >
                  <Button
                    type="primary"
                    ghost
                    style="margin-right: 10px;"
                    size="small"
                    @click="exportTemplate(item)"
                    >导出</Button
                  >
                  <Button
                    :disabled="handleBtnStatus(item)"
                    ghost
                    type="primary"
                    style="margin-right: 10px;"
                    size="small"
                    @click="addOrUpdateTemplate(item)"
                    >修改</Button
                  >
                  <Poptip confirm title="确定要删除这个模板吗？" @on-ok="delProtem(item)">
                    <Button :disabled="handleBtnStatus(item)" type="error" ghost size="small"
                      >删除</Button
                    >
                  </Poptip>
                </div>
              </div>
            </div>
          </Col>
        </Row>
        <div style="display: flex;justify-content: center;margin-bottom: 15px">
          <Page
            :total="templateTotal"
            :page-size="query.pageSize"
            :current="query.pageIndex"
            show-total
            show-elevator
            @on-change="temOnChange"
          />
        </div>
        </template>
        <NoData v-else></NoData>
      </div>
    </template>
    <!-- 导入模板 -->
    <Modal
      :mask-closable="false"
      width="650"
      :title="templateModal.title"
      v-model="templateModal.show"
      :loading="templateModal.loading"
      @on-ok="submitTemplateInfo('templateFormValidate')"
      @on-cancel="canleTemplateModal('templateFormValidate')"
    >
      <Form
        ref="templateFormValidate"
        :model="templateFormValidate"
        :rules="reTemRuleValidate"
        :label-width="60"
      >
        <FormItem label="名称" prop="name">
          <Input v-model.trim="templateFormValidate.name" placeholder="最大长度为64个字符"
          :maxlength="64"></Input>
        </FormItem>
        <FormItem label="可见范围" prop="visibility">
          <RadioGroup v-model="templateFormValidate.visibility">
            <Radio label="share">单位</Radio>
            <Radio label="private">个人</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="文件：" prop="file" v-if="templateModal.type === 'add'">
          <Upload
            v-model="templateFormValidate.file"
            :format="['json', 'JSON']"
            action="/api/virtual/template/add"
            :before-upload="handleUpload"
            style="display:inline-block;"
          >
            <Button icon="ios-cloud-upload-outline">上传</Button>
          </Upload>
          <WarningTip content="请上传json格式文件"></WarningTip>
          <div class="fileStyle" v-if="templateFormValidate.file !== null">文件名称: {{templateFormValidate.file.name }}</div>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input
            v-model.trim="templateFormValidate.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="最大长度为200个字符"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="bigModal" :footer-hide="true" width="1000" title="模板Topo图">
      <div class="modal-img-wrap">
        <img :src="setTemplateImgSrc" alt="template" style="width:100%;" />
      </div>
    </Modal>
    <Modal>
    <CreateProject ref="createProject"></CreateProject>
    </Modal>
  </MenuPage>
</template>
<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import { getTemplateData, modifyTemplate, delTemplate, importTemp } from '@/api/proTemplate.js';
import { inPutTemFile } from '@/api/homer.js';
import { getRangeAll } from '@/api/reported-data';
import { visibleMixin } from '@/mixin/study.js'
import pageTitle from '@/mixin/pageTitle';
import CreateProject from './createProject.vue';
import { debounce } from '@/libs/utils'
export default {
  name:'ProTemplate',
  components: {CreateProject},
  mixins:[visibleMixin,pageTitle],
  data() {
    return {
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      setTableHei: 'auto',
      spanNum: 4,
      // 模板列表
      templateTotal: 0,
      templateList: [],
      proTemLoading: false,
      isDisableBtn: false,
      query:{
        pageIndex:1,
        pageSize:12,
        type: 'project',
        name:'',
        visibility:'',
        rangeId:''
      },
      templateModal:{
          title:'新建工程模板',
          show:false,
          loading:true,
          type:'add'
      },
      // 修改
      templateFormValidate: {
        name: '',
        visibility: 'share',
        description: '',
        file:null,
        type:'project'
      },
      reTemRuleValidate: {
        name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        visibility: [{ required: true, message: '请选择能见度 ', trigger: 'change' }],
        file: [{ required: true, message: '请上传文件' }]
      },
      reTemplateId: '',
      bigModal: false,
      setTemplateImgSrc: '',
      rangeId:'',
      rangeAllList:[],
      defaultTemplateImg: 'this.src="' + require('../../assets/home/defImg.png') + '"',
    };
  },
  computed:{
    distributedRange() {
      return this.$store.state.user.distributedRange;
    }
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this._reTemFormValidate = { ...this.templateFormValidate };
    this._query = {...this.query};
  },
  mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    let getPage = this.$route.query.page ? this.$route.query.page : 1;
    this.query.pageIndex = getPage;
    this.queryAllRange();
    // 模板列表
    this.getProtemList();
  },
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      if (this.fullWidth >= 1900) {
        this.spanNum = 4;
        this.query.pageSize = 12;
      } else {
        this.spanNum = 6;
        this.pageSize = 18;
      }
      this.contentHei = this.fullHeight - 80 - 60 + 'px'; // 80是头部高度  60是上下padding
      this.setTableHei = this.fullHeight - 80 - 60 - 52 - 49 + 'px';
    },
    // 工程模板列表
    getProtemList() {
      this.proTemLoading = true;
      let {pageIndex,pageSize,...params} = this.query;
      getTemplateData(params,{pageIndex,pageSize})
        .then((res) => {
          if (res.data.code === 1) {
            let pateInfo = res.data.data;
            let items = pateInfo.items;
            for (let i = 0; i < items.length; i++) {
              items[i].showFlag = false;
            }
            this.templateList = items;
            this.templateTotal = pateInfo.total;
          } else {
            this.templateList = [];
            this.templateTotal = 0;
          }
          this.proTemLoading = false;
        })
        .catch((err) => {
          this.proTemLoading = false;
          console.log(err);
        });
    },
    temOnChange(val) {
      this.query.pageIndex = val;
      this.getProtemList();
    },
    debounceSearch:debounce(function(){
      this.temOnChange(1)
    },500),
    refreshTem() {
      this.query = {...this._query};
      this.temOnChange(1);
    },
    // 鼠标移入 移出
    enter(key) {
      this.$set(this.templateList[key], 'showFlag', true);
    },
    leave(key) {
      this.$set(this.templateList[key], 'showFlag', false);
    },
    // 按钮的状态
    handleBtnStatus(item) {
      return item.creator === this.USER_ID || this.isRootDesigner ? false : true;
    },
    // 删除模板
    delProtem(row) {
      delTemplate(row.id)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success({
              content: '删除成功!',
              duration: 3
            });
            this.getProtemList();
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 修改模板
    addOrUpdateTemplate(params) {
      this.templateModal.show = true;
      this.$refs.templateFormValidate.resetFields();
      this.templateFormValidate.file = null;
      if(params){
        this.templateModal.title = `修改${this.pageTitle}`;
        this.templateModal.type = 'update';
        this.reTemplateId = params.id;
        this.templateFormValidate.name = params.name;
        this.templateFormValidate.visibility = params.visibility;
        this.templateFormValidate.description = params.description;
      }else{
        this.templateModal.title = `新建${this.pageTitle}`;
        this.templateModal.type = 'add';
        this.reTemplateId = '';
        this.templateFormValidate = {...this._reTemFormValidate};
      }
    },
    submitTem(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let {detail,file,...params} = this.templateFormValidate;
          params.fileData = detail;
          inPutTemFile(params).then((data) => {
            if (data.data.code === 1) {
              this.$Message.success({
                content: '操作成功',
                duration: 3
              });
              this.templateModal.show = false;
              this.getProtemList();
            } else {
              this.$Message.error({
                content: data.data.message,
                duration: 3
              });
            }
            this.cancelLoading();
          });
        } else {
          this.cancelLoading();
          // this.$Message.error('请完善信息！');
        }
      });
    },
    cancelLoading(){
      this.templateModal.loading = false;
      setTimeout(() => {
        this.templateModal.loading = true;
      })
    },
    submitTemplateInfo(name) {
      if(this.templateModal.type === 'add'){
        this.submitTem(name);
        return
      }
      this.$refs[name].validate((valid) => {
        if (valid) {
          let params = {
            name: this.templateFormValidate.name,
            visibility: this.templateFormValidate.visibility,
            description: this.templateFormValidate.description
          };
          this.templateModal.loading = true;
          modifyTemplate(params, this.reTemplateId)
            .then((res) => {
              if (res.data.code === 1) {
                this.$Message.success({
                  content: '修改成功!',
                  duration: 3
                });
                this.templateModal.show = false;
                this.getProtemList();
              } else {
                this.$Message.error({
                  content: res.data.message,
                  duration: 3
                });
              }
              this.cancelLoading();
            })
            .catch((err) => {
              console.log(err);
              this.cancelLoading();
            });
        } else {
          this.cancelLoading();
          // this.$Message.error('请完善信息！');
        }
      });
    },
    canleTemplateModal(name) {
      this.$refs[name].resetFields();
      this.templateFormValidate.visibility = 'share';
    },
    closeDistribution() {
      this.templateModal.show = false;
    },
    changeModalStatus() {
      this.reTemplateId = '';
      this.templateFormValidate.name = '';
      this.templateFormValidate.visibility = '';
      this.templateFormValidate.description = '';
    },
    // 导出工程模板
    exportTemplate(row) {
      let id = row.id;
      let name = row.name;
      importTemp(id)
        .then((res) => {
          var disp = res.headers['content-disposition'];
          if (disp && disp.search('attachment') != -1) {
            //判断是否为文件
            let projectTopo_json = JSON.stringify(res.data);
            if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
              //兼容ie10
              var blob = new Blob([projectTopo_json], {
                type: 'data:application/json;charset=utf-8'
              });
              navigator.msSaveOrOpenBlob(blob, name + '.json');
            } else {
              const a = document.createElement('a');
              a.style.visibility = 'hidden';
              document.body.appendChild(a);
              var blobs = new Blob([projectTopo_json], {
                type: 'data:application/json;charset=utf-8'
              });
              var objurl = URL.createObjectURL(blobs);
              a.href = objurl;
              a.download = name + '.json';
              a.click();
              document.body.removeChild(a);
            }
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {});
    },
    // 创建工程
    creatProByTemp(template) {
      this.$refs.createProject.openModal(template)
    },
    // 图片路径处理
    setFiles(src){
      if(src){
        return '/files' + src;
      }else{
        return require('../../assets/home/defImg.png');
      }
    },
    // 大图预览
    showBigImg(src) {
      if (src) {
        this.setTemplateImgSrc = '/files' + src;
        this.bigModal = true;
      } else {
        this.$Message.info({ content: '无缩略图', duration: 3 });
      }
    },
    //查询所有分靶场信息
    queryAllRange() {
      getRangeAll().then((res) => {
        if (res.code === 1) {
          this.rangeAllList = res.data;
        }
      });
    },
    handleUpload(file) {
      let _this = this;
      let nameArr = file.name.split('.');
      let fileType = nameArr[nameArr.length - 1];
      if (fileType !== 'json' && fileType !== 'JSON') {
        _this.$Message.error({
          content: '请选择json文件',
          duration: 5
        });
        return false;
      }
      this.templateFormValidate.file = file;
      this.$refs.templateFormValidate.validateField('file');
      const reader = new FileReader();
      reader.readAsText(this.templateFormValidate.file, 'UTF-8');
      reader.onload = function(evt) {
        let newjson = evt.target.result;
        _this.templateFormValidate.detail = newjson;
        // this.result为读取到的json字符串，需转成json对象
        // 检测是否导入成功
      };
      let name = file.name;
      let fileName = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
      if (
        fileName !== 'json' &&
        fileName !== 'JSON' &&
        fileName !== 'xml' &&
        fileName !== 'ymal' &&
        fileName !== 'sql'
      ) {
        this.templateFormValidate.file = null;
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件格式' + file.name + '不正确，请上载.json/.xml/.ymal/.sql文件。'
        });
      }
      return false;
    },
  }
};
</script>
<style scoped>
.table-wrap {
  flex:auto;
  /* padding: 0 30px; */
  overflow-x: hidden;
  overflow-y: auto;
}
.deviceDrawer {
  position: relative;
}
.exper-wrap {
  margin-bottom: 15px;
  position: relative;
  height: 205px;
  /* cursor: pointer; */
  padding-top: 5px;
}
.exper-wrap:hover {
  box-shadow: 0px 0px 10px #a9a9a9;
}
.exper-avtar {
  height: 13px;
  width: 11px;
  vertical-align: middle;
  display: inline-block;
  margin-right: 5px;
  margin-top: -3px;
}
.time-icon {
  height: 11px;
  width: 11px;
  vertical-align: middle;
  display: inline-block;
  margin-right: 5px;
  margin-top: -2px;
}
.ses-icon {
  height: 9px;
  width: 15px;
  vertical-align: middle;
  display: inline-block;
  margin-right: 5px;
  margin-top: -2px;
}
.exper-img {
  width: 100%;
  height: 120px;
  border-radius: 6px 6px 0px 0px;
  border: 1px solid var(--card-line-color);
  cursor: zoom-in;
}
.exper-bottom {
  border-radius: 0 0px 6px 6px;
  border-left: 1px solid var(--card-line-color);
  border-bottom: 1px solid var(--card-line-color);
  border-right: 1px solid var(--card-line-color);
  padding: 10px 10px 10px 10px;
  margin-top: -6px;
  position: absolute;
  /* left: 12px; */
  bottom: 5px;
  width: calc(100% - 24px);
  background-color:var(--imagecard-botton-bgcolor);
}
.oper-btn {
  display: flex;
  justify-content: flex-start;
  margin: 10px 0;
  /*transition: display 1s;*/
}
.exper-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 5px;
}
.modal-img-wrap {
  width: 100%;
  display: flex;
  justify-content: center;
  overflow: auto;
}
</style>
<style>
.deviceDrawer .ivu-drawer-body {
  overflow: inherit;
}
</style>
